package com.yihuier.yihuier.Controller.UserManager;

import com.yihuier.yihuier.Controller.Common.FileController;
import com.yihuier.yihuier.Controller.Common.FileUploadController;
import com.yihuier.yihuier.Controller.Common.TimeJudgeController;
import com.yihuier.yihuier.Entity.MeetingManager.DTO.SendMessageDTO;
import com.yihuier.yihuier.Entity.MeetingManager.MeetingRoom;
import com.yihuier.yihuier.Entity.RoomManager.AccessControl;
import com.yihuier.yihuier.Entity.RoomManager.Room;
import com.yihuier.yihuier.Entity.UserManager.Department;
import com.yihuier.yihuier.Entity.UserManager.User;
import com.yihuier.yihuier.Service.MeetingManager.MeetingAttendService;
import com.yihuier.yihuier.Service.MeetingManager.MeetingRoomService;
import com.yihuier.yihuier.Service.MeetingManager.MeetingService;
import com.yihuier.yihuier.Service.MeetingManager.MeetingUserService;
import com.yihuier.yihuier.Service.RoomManager.AccessControlService;
import com.yihuier.yihuier.Service.RoomManager.RoomService;
import com.yihuier.yihuier.Service.UserManager.*;
import com.yihuier.yihuier.Util.QRCodeUtil;
import com.yihuier.yihuier.Util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/UserManager/Managers/")
public class ManagerController {
    @Autowired
    private UserService userService;

    @Autowired
    private ManagerService managerService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private AccessControlService accessControlService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DepartmentUserService departmentUserService;

    @Autowired
    private MeetingAttendService meetingAttendService;

    @Autowired
    MeetingUserService meetingUserService;

    @Autowired
    MeetingRoomService meetingRoomService;

    @Autowired
    MessageService messageService;

    @Autowired
    MeetingService meetingService;

    @Autowired
    TimeJudgeController timeJudgeController;

    @PostMapping("managerNameAndHeaderPic.json")
    public ResponseMessage getManagerNameAndHeaderPic(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        String manager_name = managerService.getManagerNameByManagerId(manager_id);
        if (manager_name == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户已被注销");
        }
        LinkedHashMap<String, String> data = new LinkedHashMap<>();
        data.put("manager_name", manager_name);
        data.put("manager_header_pic", "http://39.108.10.155:80/file/user_header_pic/manager.jpg");
        return new ResponseMessage(ResponseMessage.SUCCESS, "请求成功", data);
    }

    /**
     * 添加会议室
     */
    @PostMapping("addMeetingRoom.do")
    public ResponseMessage addMeetingRoom(@PathParam("room_name") String room_name, @PathParam("room_capacity") String room_capacity, @PathParam("room_hardware") String room_hardware, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int company_id = managerService.getCompanyIdByManagerId(manager_id);
        int room_id = roomService.insertRoom(room_name, room_capacity, company_id, room_hardware);
        QRCodeUtil.zxingCodeCreate("1," + room_id, "1" + room_id, 250);//创建会议室的二维码
        if (room_id != 0) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "会议室添加成功");
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "数据库错误");
    }

    /**
     * 返回所在公司的所有会议室信息（管理员权限）
     */
    @PostMapping("RoomsManager.json")
    public ResponseMessage getCompanyIdByManagerId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int company_id = managerService.getCompanyIdByManagerId(manager_id);
        List<Room> Rooms = roomService.getRoomsByCompanyId(company_id);
        ArrayList<Map<String, Object>> RoomsData = new ArrayList<Map<String, Object>>();
        for (Room room : Rooms) {
            LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>();
            data.put("room_id", room.getRoom_id());
            data.put("room_name", room.getRoom_name());
            data.put("room_capacity", room.getRoom_capacity());
            AccessControl lockObj = accessControlService.getAccessControlObj(room.getRoom_lock());
            data.put("room_lock", lockObj);
            data.put("room_parentstatus", room.getRoom_parentstatus());
            data.put("room_status", room.getRoom_status());
            data.put("room_if_occupy", room.getRoom_if_occupy());
            data.put("room_pic_url", FileController.filePathDispose(room.getRoom_pic_url()));
            data.put("room_advertisement", room.getRoom_advertisement());
            String[] hardware = room.getRoom_hardware().split(",");
            data.put("room_hardware", hardware);
            RoomsData.add(data);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "管理员获取所有会议室状态", RoomsData);
    }

    /**
     * 修改会议室名称
     */
    @PostMapping("updateRoomName.do")
    public ResponseMessage updateRoomName(@PathParam("room_id") int room_id, @PathParam("room_name") String room_name) {
        int result = roomService.setRoomNameByRoomId(room_id, room_name);
        if (result == 1) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "管理员修改会议室名称成功");
        } else {
            return new ResponseMessage(ResponseMessage.ERROR, "该会议室已被注销", result);
        }
    }

    /**
     * 修改会议室容量
     */
    @PostMapping("updateRoomCapacity.do")
    public ResponseMessage updateRoomCapacity(@PathParam("room_id") String room_id, @RequestParam("room_capacity") String room_capacity, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int result = roomService.setRoomCapacityByRoomId(room_id, room_capacity);
        if (result == 1) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "管理员修改会议室容量成功");
        } else {
            return new ResponseMessage(ResponseMessage.ERROR, "该会议室已被注销");
        }
    }

    /**
     * 修改会议室状态 维修/正常使用
     */
    @PostMapping("updateRoomParentstatus.do")
    public ResponseMessage updateRoomParentstatus(@PathParam("room_id") String room_id, @RequestParam("room_parentstatus") String room_parentstatus, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int result = roomService.setRoomParentstatusByRoomId(room_id, room_parentstatus);
        if (result == 1) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "管理员修改会议室状态成功");
        } else {
            return new ResponseMessage(ResponseMessage.ERROR, "该会议室已被注销");
        }
    }

    /**
     * 删除/取消删除会议室
     */
    @PostMapping("updateRoomStatus.do")
    public ResponseMessage updateRoomStatus(@PathParam("room_id") String room_id, @RequestParam("room_status") String room_status, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int result = roomService.setRoomStatusByRoomId(room_id, room_status);
        if (result == 1) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "管理员修改会议室状态成功");
        } else {
            return new ResponseMessage(ResponseMessage.ERROR, "该会议室已被注销");
        }
    }

    /**
     * 管理员显示所有用户信息
     */
    @PostMapping("getPersonalCompanyUsers.json")
    public ResponseMessage getPersonlCompanyUsers(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id != null) {
            ArrayList<Map<Object, Object>> personalCompanyDepartmentUsers = new ArrayList<Map<Object, Object>>();
            int company_id = managerService.getCompanyIdByManagerId(manager_id);
            ArrayList<Department> Departments = departmentService.getDepartmentIdsAndDepartmentNames(company_id);
            for (Department department : Departments) {
                ArrayList<HashMap<Object, Object>> userList = new ArrayList<HashMap<Object, Object>>();
                HashMap<Object, Object> maptight = new HashMap<Object, Object>();
                maptight.put("department_id", department.getDepartment_id());
                maptight.put("department_name", department.getDepartment_name());
                ArrayList<Integer> user_ids = departmentUserService.getUsersByDepartmentId(department.getDepartment_id());//获得所在部门的所有用户编号1，4
                for (int personal_user_id : user_ids) {
                    HashMap<Object, Object> userMap = new HashMap<Object, Object>();
                    User specified_user = userService.getUserinfomationByUseridForManager(personal_user_id);
                    userMap.put("user_id", specified_user.getUser_id());
                    userMap.put("user_name", specified_user.getUser_name());
                    userMap.put("user_headpic_dir", FileController.filePathDispose(specified_user.getUser_headpic_dir()));
                    userMap.put("user_email", specified_user.getUser_email());
                    userMap.put("user_status", specified_user.getUser_status());
                    userList.add(userMap);//该部门新显示一个用户信息
                }//该部门所有用户添加完成
                maptight.put("users", userList);//将该部门的所有部件安装完成
                personalCompanyDepartmentUsers.add(maptight);//组装好所有信息
            }
            return new ResponseMessage(ResponseMessage.SUCCESS, "根据用户编号分组获取所在公司所有用户", personalCompanyDepartmentUsers);
        }
        return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
    }

    /**
     * 添加用户
     */
    @PostMapping("addAccountInfomation.json")
    public ResponseMessage addAccount(@PathParam("department_id") int department_id, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        String yearLast = new SimpleDateFormat("yy", Locale.CHINESE).format(Calendar.getInstance().getTime());
        int company_id = departmentService.getCompanyIdByDepartmentId(department_id);
        String seqCompanyId = String.format("%03d", company_id);
        String seqDepartmentId = String.format("%05d", department_id);
        int usersNum = departmentUserService.getSumOfUsersInDepartment(department_id) + 1;
        String seqUsers = String.format("%03d", usersNum);
        String Combination = yearLast + seqCompanyId + seqDepartmentId + seqUsers;
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户账号取得成功", Combination);
    }

    /**
     * 添加用户
     */
    @PostMapping("addUser.do")
    public ResponseMessage addUser(@PathParam("department_id") int department_id, @PathParam("user_name") String user_name, @PathParam("user_account") String user_account, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int addUserResult = userService.addUser(user_name, user_account, user_account);//在user表中添加账号
        if (addUserResult == 1) {
            int user_id = userService.getUserIdByAccountAndPassword(user_name, user_account, user_account);
            int addDepartmentUserResult = departmentUserService.addDepartmentUser(department_id, user_id);//在department_user表中添加对象
            if (addDepartmentUserResult == 1) {
                return new ResponseMessage(ResponseMessage.SUCCESS, "添加用户成功");
            }
            return new ResponseMessage(ResponseMessage.ERROR, "在部门用户表中添加用户失败");
        }
        return new ResponseMessage(ResponseMessage.ERROR, "在用户表中添加用户失败");
    }

    /**
     * 删除用户
     */
    @PostMapping("deleteUser.do")
    public ResponseMessage deleteUser(String user_id, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int result = userService.deleteUser(user_id);
        if (result == 1) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "用户删除成功");
        }
        return new ResponseMessage(ResponseMessage.ERROR, "数据库错误");
    }

    /**
     * 添加部门
     */
    @PostMapping("addDepartment.do")
    public ResponseMessage addDepartment(@PathParam("department_name") String department_name, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id != null) {
            int company_id = managerService.getCompanyIdByManagerId(manager_id);
            int addResult = departmentService.addDepartment(department_name, company_id);
            if (addResult == 1) {
                return new ResponseMessage(ResponseMessage.SUCCESS, "部门添加成功");
            }
            return new ResponseMessage(ResponseMessage.ERROR, "数据库错误");
        }
        return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
    }

    @PostMapping("allMessagesSendFromMe.json")
    public ResponseMessage allMessagesSendFromMe(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id_ath = (String) session.getAttribute("manager_id");
        if (manager_id_ath == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int manager_id = Integer.parseInt(manager_id_ath);
        List<Map<String, Object>> allMessageInfo = messageService.getAllMessageFromManagerSelf(manager_id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设定时间格式规范
        for (int i = 0; i < allMessageInfo.size(); i++) {
            allMessageInfo.get(i).put("message_datetime", sdf.format(allMessageInfo.get(i).get("message_datetime")));
            String tempObj = "" + allMessageInfo.get(i).get("message_to_id");
            int user_department_id = departmentUserService.getDepartmentIdByUserId(Integer.parseInt(tempObj));
            String user_department_name = departmentService.getDepartmentNameById(user_department_id);
            String user_name = userService.getUserNameByUserId("" + allMessageInfo.get(i).get("message_to_id"));
            String combine_name = user_department_name + "-" + user_name;
            allMessageInfo.get(i).put("message_to_user", combine_name);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "请求成功", allMessageInfo);
    }

    @PostMapping("sendMessage.do")
    public ResponseMessage sendMessage(@RequestBody SendMessageDTO sendMessageDTO, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id_ath = (String) session.getAttribute("manager_id");
        if (manager_id_ath == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int manager_id = Integer.parseInt(manager_id_ath);
        for (int id : sendMessageDTO.getUser_ids()) {
            messageService.addMessage(manager_id, id, sendMessageDTO.getMessage_content());//向message表中添加消息
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "消息发送成功");
    }

    @PostMapping("allMeetings.json")
    public ResponseMessage getAllMeeting(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id_ath = (String) session.getAttribute("manager_id");
        if (manager_id_ath == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设定时间格式规范
        ArrayList<Map<String, Object>> allMeetings = new ArrayList<Map<String, Object>>();
        int company_id = managerService.getCompanyIdByManagerId(manager_id_ath);
//        List<Room> Rooms = roomService.getRoomsByCompanyId(company_id);
        int[] room_ids = roomService.getCompanyRoomIds(company_id);
        if (room_ids.length == 0){
            return new ResponseMessage(ResponseMessage.ERROR, "本公司尚未添加会议室",allMeetings);
        }

        int[] meeting_ids = meetingRoomService.getMeetingIds(room_ids);
        for (int meeting_id : meeting_ids){
            timeJudgeController.updateMeetingAndPersonStatus(meeting_id);//更新所有会议及人员信息信息
            Map<String,Object> tempData = meetingService.getMeetingInfoByMeetingId(meeting_id);
            LinkedHashMap<String,Object> littleData = new LinkedHashMap<>();
            littleData.put("meeting_id",tempData.get("meeting_id"));
            String temp = ""+tempData.get("location");
            String roomName = roomService.getRoomNameByRoomId(Long.parseLong(temp));
            String tempmeeting_id = ""+tempData.get("meeting_id");
            Map<String,Object> meetingTimeAndLast =  meetingRoomService.getMeetingTimes(Long.parseLong(temp),Long.parseLong(tempmeeting_id));
            if (meetingTimeAndLast == null){
                littleData.put("meeting_time_start","测试数据不全");
                littleData.put("lastTime","测试数据不全");
            }else{
                littleData.put("meeting_time_start",sdf.format(meetingTimeAndLast.get("meeting_time_start")));
                littleData.put("lastTime",meetingTimeAndLast.get("meeting_time"));
            }
            littleData.put("meeting_name",tempData.get("meeting_name"));
            littleData.put("description",tempData.get("description"));
            littleData.put("meeting_status",tempData.get("meeting_status"));
            littleData.put("location",roomName);
            int[] attendUsersIds = meetingUserService.gettAttendUsersIds((Long)tempData.get("meeting_id"));
            List<Map<String,Object>> userInfo = userService.getUsersByUserIds(attendUsersIds);
            for (int i=0;i<userInfo.size();i++) {
                userInfo.get(i).put("user_headpic_dir",FileController.filePathDispose((String)userInfo.get(i).get("user_headpic_dir")));
            }
            littleData.put("people",userInfo);
            allMeetings.add(littleData);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "请求成功",allMeetings);
    }

    /**
     * 用户申请参加会议审核
     */
    @PostMapping("allApply.json")
    public ResponseMessage getAllApplyUsers(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int company_id = managerService.getCompanyIdByManagerId(manager_id);//获取管理员所在公司id
        int[] room_ids = roomService.getCompanyRoomIds(company_id);//获取管理员所在公司的全部会议室
        if (room_ids.length == 0) {
            return new ResponseMessage(ResponseMessage.ERROR, "本公司尚未添加会议室,并无用户申请参会");
        }
        int[] meeting_ids = meetingRoomService.getMeetingIds(room_ids);
        List<Map<String,Integer>> userAndMeetingInfo = meetingUserService.getMeetingApplyUsers(meeting_ids);
        if (userAndMeetingInfo.size() == 0){
            return new ResponseMessage(ResponseMessage.ERROR, "尚无用户申请参会");
        }
        ArrayList<Map<String,Object>> Data = new ArrayList<Map<String,Object>>();
        for (int i=0;i<userAndMeetingInfo.size();i++){
            LinkedHashMap<String,Object> littleData = new LinkedHashMap<String,Object>();
            String tempMeeting_id = ""+userAndMeetingInfo.get(i).get("meeting_id");
            Map<String, Object> tempData = meetingService.getMeetingInfoByMeetingId(Integer.parseInt(tempMeeting_id));
            littleData.put("meeting_id",userAndMeetingInfo.get(i).get("meeting_id"));
            littleData.put("meeting_name",tempData.get("meeting_name"));
            littleData.put("description",tempData.get("description"));
            String room_name = roomService.getRoomNameByRoomId((Long) tempData.get("location"));
            littleData.put("location",room_name);
            littleData.put("meeting_status",tempData.get("meeting_status"));
            littleData.put("user_id",userAndMeetingInfo.get(i).get("user_id"));
            String temp_user_id = ""+userAndMeetingInfo.get(i).get("user_id");
            int user_department_id = departmentUserService.getDepartmentIdByUserId(Integer.parseInt(temp_user_id));
            String user_department_name = departmentService.getDepartmentNameById(user_department_id);
            String user_name = userService.getUserNameByUserId("" + userAndMeetingInfo.get(i).get("user_id"));
            String combine_name = user_department_name + "-" + user_name;
            littleData.put("user_name",combine_name);
            Data.add(littleData);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "请求成功",Data);
    }

    @PostMapping("checkApply.do")
    public ResponseMessage checkApply(@PathParam("user_id") int user_id,@PathParam("meeting_id") int meeting_id,@PathParam("status") int status,HttpServletRequest request){
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        if (status == 1){
            int result = meetingUserService.checkApply(user_id,meeting_id,status);
            if (result == 1){
                meetingAttendService.addOneRecordOfMeetingUserWithOutReason(user_id,meeting_id);//往meeting_attend表中添加数据
                String username = userService.getUserNameByUserId(""+user_id);
                String meeting_name = meetingService.getMeetingNameById(meeting_id);
                String message_content = "你好 "+username+",你申请参加 "+meeting_name+" 会议，已通过审核";
                int message_from_id = Integer.parseInt(manager_id);
                messageService.addMessage(message_from_id,user_id,message_content);//向消息表中插入数据
                return new ResponseMessage(ResponseMessage.SUCCESS, "请求成功");
            }
        }else if (status == 3){
            int result =meetingUserService.checkApply(user_id,meeting_id,status);
            if (result == 1){
                String username = userService.getUserNameByUserId(""+user_id);
                String meeting_name = meetingService.getMeetingNameById(meeting_id);
                String message_content = "你好 "+username+",你申请参加 "+meeting_name+" 会议,被拒绝";
                int message_from_id = Integer.parseInt(manager_id);
                messageService.addMessage(message_from_id,user_id,message_content);//向消息表中插入数据
                return new ResponseMessage(ResponseMessage.SUCCESS, "请求成功");
            }
        }
        return new ResponseMessage(ResponseMessage.ERROR, "数据格式错误");
    }

}
